<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>工程师答题系统 - 离线版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .app-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            max-width: 400px;
            width: 100%;
            min-height: 600px;
            display: flex;
            flex-direction: column;
        }
        
        .app-header {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 10px 20px;
            text-align: center;
            border-radius: 20px 20px 0 0;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .app-title {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 0px;
        }
        
        .app-subtitle {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .answer-hint {
            font-size: 14px;
            margin-top: 5px;
            padding: 5px 10px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 10px;
            display: none;
        }
        
        .loading-screen {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px;
        }
        
        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-text {
            color: #666;
            font-size: 16px;
        }
        
        .quiz-container {
            flex: 1;
            padding: 20px;
            display: none;
        }
        
        .question-card {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .question-number {
            color: #667eea;
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .question-text {
            font-size: 16px;
            line-height: 1.6;
            color: #333;
            margin-bottom: 20px;
        }
        
        .options-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .option-btn {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 12px;
            padding: 15px;
            text-align: left;
            font-size: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .option-btn:hover {
            border-color: #667eea;
            transform: translateY(-2px);
        }
        
        .option-btn.selected {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        
        .option-btn.correct-selected {
            background: #28a745;
            color: white;
            border-color: #28a745;
        }
        
        .option-btn.correct-not-selected {
            background: #90EE90;
            color: #000000;
            border-color: #90EE90;
        }
        
        .option-btn.incorrect {
            background: #dc3545;
            color: white;
            border-color: #dc3545;
        }
        
        .controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            background: white;
            border-radius: 0 0 20px 20px;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
        }
        
        .button-group {
            display: flex;
            gap: 10px;
        }
        
        .progress {
            font-size: 14px;
            color: #666;
        }
        
        .nav-btn {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 10px 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .nav-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .nav-btn:not(:disabled):hover {
            background: #5a6fd8;
            transform: translateY(-1px);
        }
        
        .result-screen {
            flex: 1;
            display: none;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px;
            text-align: center;
        }
        
        .result-title {
            font-size: 28px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .result-score {
            font-size: 48px;
            font-weight: bold;
            color: #28a745;
            margin-bottom: 10px;
        }
        
        .result-text {
            font-size: 16px;
            color: #666;
            margin-bottom: 30px;
        }
        
        .restart-btn {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 15px 30px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .restart-btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .mode-selection {
            flex: 1;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 40px 20px;
        }
        
        .mode-title {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 30px;
            text-align: center;
        }
        
        .mode-buttons {
            display: flex;
            flex-direction: column;
            gap: 15px;
            width: 100%;
            max-width: 300px;
        }
        
        .mode-btn {
            background: #667eea;
            color: white;
            border: none;
            border-radius: 25px;
            padding: 15px 20px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .mode-btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        
        .mode-btn:active {
            transform: translateY(0);
        }
        
        /* 底部导航栏样式 */
        .bottom-nav {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 10px 0;
            z-index: 1000;
        }
        
        .nav-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
            padding: 5px 10px;
            border-radius: 10px;
        }
        
        .nav-item:hover {
            background: #f8f9fa;
        }
        
        .nav-item.active {
            color: #667eea;
        }
        
        .nav-icon {
            font-size: 20px;
        }
        
        .nav-text {
            font-size: 12px;
            text-align: center;
        }
        
        /* 调整主容器以适应底部导航 */
        .app-container {
            margin-bottom: 70px;
        }
        
        /* 设置界面样式 */
        .settings-screen {
            flex: 1;
            display: none;
            flex-direction: column;
            padding: 20px;
        }
        
        .settings-title {
            font-size: 20px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .settings-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .settings-label {
            font-size: 14px;
            color: #333;
        }
        
        .settings-value {
            font-size: 14px;
            color: #666;
        }
        
        /* 设置选择框样式 */
        .settings-select {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 8px 12px;
            font-size: 14px;
            color: #333;
            cursor: pointer;
            outline: none;
            transition: border-color 0.3s ease;
        }
        
        .settings-select:hover {
            border-color: #667eea;
        }
        
        .settings-select:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        /* 开关按钮样式 */
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: #667eea;
        }
        
        input:checked + .slider:before {
            transform: translateX(26px);
        }
    </style>
</head>
<body>
    <div class="app-container">
        <div class="app-header">
            <div class="app-title">工程师答题系统</div>
            <div style="display: flex; align-items: center; gap: 10px;">
                <div class="answer-hint" id="answerHint"></div>
                <button class="nav-btn" id="finishBtn" onclick="finishQuiz()" style="display: none; padding: 8px 16px; font-size: 12px;">交卷</button>
            </div>
        </div>
        
        <div class="loading-screen" id="loadingScreen">
            <div class="spinner"></div>
            <div class="loading-text">正在加载题库...</div>
        </div>
        
        <div class="mode-selection" id="modeSelection" style="display: none;">
            <div class="mode-title">选择答题模式</div>
            <div class="mode-buttons">
                <button class="mode-btn" onclick="startNormalMode()">顺序答题</button>
                <button class="mode-btn" onclick="startRandomMode()">随机答题</button>
                <button class="mode-btn" onclick="startWrongMode()">错题本</button>
            </div>
        </div>
        
        <div class="quiz-container" id="quizContainer">
            <div class="question-card">
                <div class="question-number" id="questionNumber">第1题<span id="timerDisplay" style="margin-left: auto; color: #667eea;"></span></div>
                <div class="question-text" id="questionText">正在加载题目...</div>
                <div class="options-container" id="optionsContainer"></div>
            </div>
        </div>
        
        <div class="result-screen" id="resultScreen">
            <div class="result-title">答题完成！</div>
            <div class="result-score" id="finalScore">0</div>
            <div class="result-text">恭喜您完成所有题目</div>
            <button class="restart-btn" onclick="restartQuiz()">重新开始</button>
        </div>
        
        <div class="controls" id="controls" style="display: none;">
            <div class="progress" id="progress">1/357</div>
            <div class="button-group">
                <button class="nav-btn" id="prevBtn" onclick="previousQuestion()">上一题</button>
                <button class="nav-btn" id="submitBtn" onclick="submitAnswer()" style="display: none;">确定</button>
                <button class="nav-btn" id="nextBtn" onclick="nextQuestion()">下一题</button>
            </div>
        </div>
        
        <!-- 设置界面 -->
        <div class="settings-screen" id="settingsScreen">
            <div class="settings-title">设置</div>
            
            <!-- 每次刷题数量设置 -->
            <div class="settings-item">
                <div class="settings-label">每次刷题数量</div>
                <select class="settings-select" id="questionCount" onchange="saveQuestionCount()">
                    <option value="10">10题</option>
                    <option value="20">20题</option>
                    <option value="50">50题</option>
                    <option value="80">80题</option>
                    <option value="100">100题</option>
                    <option value="1217">全部</option>
                </select>
            </div>
            
            <!-- 答题模式设置 -->
            <div class="settings-item">
                <div class="settings-label">考试模式</div>
                <label class="switch">
                    <input type="checkbox" id="examMode" onchange="saveExamMode()">
                    <span class="slider"></span>
                </label>
            </div>
            
            <!-- 计时器设置 -->
            <div class="settings-item">
                <div class="settings-label">计时器</div>
                <label class="switch">
                    <input type="checkbox" id="timerEnabled" onchange="saveTimerSetting()">
                    <span class="slider"></span>
                </label>
            </div>
            
            <div class="settings-item">
                <div class="settings-label">清除错题记录</div>
                <button class="nav-btn" onclick="clearWrongQuestions()">清除</button>
            </div>
            <div class="settings-item">
                <div class="settings-label">已完成数量</div>
                <div class="settings-value" id="completedCount">0</div>
            </div>
            <div class="settings-item">
                <div class="settings-label">题目总数</div>
                <div class="settings-value" id="totalQuestions">0</div>
            </div>
            <div class="settings-item">
                <div class="settings-label">错题数量</div>
                <div class="settings-value" id="wrongCount">0</div>
            </div>
        </div>
    </div>
    
    <!-- 底部导航栏 -->
    <div class="bottom-nav">
        <div class="nav-item" id="navNormal" onclick="switchMode('normal')">
            <div class="nav-icon">📝</div>
            <div class="nav-text">顺序答题</div>
        </div>
        <div class="nav-item" id="navRandom" onclick="switchMode('random')">
            <div class="nav-icon">🎲</div>
            <div class="nav-text">随机答题</div>
        </div>
        <div class="nav-item" id="navWrong" onclick="switchMode('wrong')">
            <div class="nav-icon">❌</div>
            <div class="nav-text">错题本</div>
        </div>
        <div class="nav-item" id="navSettings" onclick="switchMode('settings')">
            <div class="nav-icon">⚙️</div>
            <div class="nav-text">设置</div>
        </div>
    </div>

    <script>
        // 题库数据
        let questions = [];
        let originalQuestions = []; // 保存原始题库
        let currentQuestion = 0;
        let userAnswers = {};
        let score = 0;
        let answerSubmitted = {}; // 跟踪每道题是否已提交答案
        let currentMode = 'normal'; // 当前答题模式：normal, random, wrong
        let wrongQuestions = []; // 错题本
        
        // 用户统计数据
        let userStats = {
            completedQuestions: 0,
            correctAnswers: 0,
            completedQuestionsList: [] // 记录已完成的题目ID
        };
        
        // 新增设置相关变量
        let settings = {
            questionCount: 20, // 每次刷题数量，默认20题
            examMode: 'normal', // 答题模式：normal正常模式，exam考试模式
            timerEnabled: false // 计时器是否开启
        };
        let timerInterval = null; // 计时器引用
        let timerSeconds = 0; // 计时器秒数

        // 加载题库数据
        async function loadQuestions() {
            try {
                console.log('正在加载题库...');
                
                // 尝试多种加载方式
                let questionsData = null;
                
                // 方式1：优先从questions.js加载（直接双击运行时使用）
                try {
                    // 检查是否已经有questions.js加载的数据
                    if (window.questionsData && Array.isArray(window.questionsData) && window.questionsData.length > 0) {
                        questionsData = window.questionsData;
                        console.log(`成功从questions.js加载${questionsData.length}道题目`);
                        processLoadedQuestions(questionsData);
                        return;
                    }
                    
                    // 动态加载questions.js
                    const script = document.createElement('script');
                    script.src = './questions.js';
                    script.onload = () => {
                        if (window.questionsData && Array.isArray(window.questionsData) && window.questionsData.length > 0) {
                            questionsData = window.questionsData;
                            console.log(`成功从questions.js加载${questionsData.length}道题目`);
                            processLoadedQuestions(questionsData);
                        } else if (typeof questions !== 'undefined' && Array.isArray(questions) && questions.length > 0) {
                            questionsData = questions;
                            console.log(`成功从questions.js加载${questionsData.length}道题目`);
                            processLoadedQuestions(questionsData);
                        } else {
                            console.error('questions.js加载成功但数据格式错误');
                            // 继续尝试其他方式
                            tryOtherLoadMethods();
                        }
                    };
                    script.onerror = () => {
                        console.log('questions.js加载失败，尝试其他方式');
                        tryOtherLoadMethods();
                    };
                    document.head.appendChild(script);
                    return;
                    
                } catch (e) {
                    console.log('questions.js加载失败:', e.message);
                    tryOtherLoadMethods();
                }
                
                // 其他加载方式的辅助函数
                function tryOtherLoadMethods() {
                    // 方式2：尝试从外部文件加载（Web服务器环境下使用）
                    try {
                        fetch('./questions.json')
                            .then(response => {
                                if (response.ok) {
                                    return response.json();
                                } else {
                                    throw new Error('JSON文件加载失败');
                                }
                            })
                            .then(data => {
                                questionsData = data;
                                console.log(`成功从questions.json加载${questionsData.length}道题目`);
                                processLoadedQuestions(questionsData);
                            })
                            .catch(e => {
                                console.log('questions.json加载失败，尝试localStorage:', e.message);
                                // 方式3：使用localStorage中的备份数据
                                const backupData = localStorage.getItem('questionsBackup');
                                if (backupData) {
                                    questionsData = JSON.parse(backupData);
                                    console.log(`从localStorage备份加载${questionsData.length}道题目`);
                                    processLoadedQuestions(questionsData);
                                } else {
                                    handleLoadFailure();
                                }
                            });
                    } catch (e) {
                        console.log('fetch请求失败:', e.message);
                        // 方式3：使用localStorage中的备份数据
                        const backupData = localStorage.getItem('questionsBackup');
                        if (backupData) {
                            questionsData = JSON.parse(backupData);
                            console.log(`从localStorage备份加载${questionsData.length}道题目`);
                            processLoadedQuestions(questionsData);
                        } else {
                            handleLoadFailure();
                        }
                    }
                }
                
            } catch (error) {
                console.error('加载题库失败:', error);
                handleLoadFailure();
            }
        }
        
        function handleLoadFailure() {
            questions = [];
            originalQuestions = [];
            console.error('题库加载失败');
            
            // 隐藏加载界面，显示错误信息
            document.getElementById('loadingScreen').style.display = 'none';
            document.getElementById('quizContainer').style.display = 'none';
            
            // 创建错误提示
            const errorDiv = document.createElement('div');
            errorDiv.innerHTML = `
                <div style="padding: 40px; text-align: center; color: #666;">
                    <h3>题库加载失败</h3>
                    <p>请尝试以下方法：</p>
                    <ol style="text-align: left; max-width: 300px; margin: 20px auto;">
                        <li>确保网络连接正常</li>
                        <li>刷新页面重试</li>
                        <li>使用index.html入口页面</li>
                        <li>检查文件是否完整</li>
                    </ol>
                    <button onclick="window.location.reload()" style="margin: 10px; padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 5px; cursor: pointer;">
                        重新加载
                    </button>
                    <button onclick="window.location.href='index.html'" style="margin: 10px; padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 5px; cursor: pointer;">
                        使用入口页面
                    </button>
                </div>
            `;
            document.querySelector('.loading-screen').parentNode.appendChild(errorDiv);
            document.querySelector('.loading-screen').style.display = 'none';
        }
        
        // 处理已加载的题目数据
        function processLoadedQuestions(questionsData) {
            questions = questionsData;
            originalQuestions = [...questions];
            
            // 保存到localStorage作为备份
            localStorage.setItem('questionsBackup', JSON.stringify(questions));
            
            // 从localStorage加载错题记录
            const savedWrongQuestions = localStorage.getItem('wrongQuestions');
            if (savedWrongQuestions) {
                wrongQuestions = JSON.parse(savedWrongQuestions);
                console.log(`加载${wrongQuestions.length}道错题`);
            }
            
            // 从localStorage加载设置
            const savedSettings = localStorage.getItem('settings');
            if (savedSettings) {
                settings = JSON.parse(savedSettings);
                console.log('加载设置成功');
            } else {
                console.log('使用默认设置');
            }
            
            // 从localStorage加载用户统计数据
            const savedUserStats = localStorage.getItem('userStats');
            if (savedUserStats) {
                userStats = JSON.parse(savedUserStats);
                if (!userStats.completedQuestionsList) {
                    userStats.completedQuestionsList = [];
                }
                console.log('加载用户统计数据成功');
            } else {
                userStats = {
                    completedQuestions: 0,
                    correctAnswers: 0,
                    completedQuestionsList: []
                };
                console.log('使用默认用户统计数据');
            }
            
            // 更新界面
            updateSettingsInfo();
            
            // 隐藏加载界面
            document.getElementById('loadingScreen').style.display = 'none';
            
            // 根据考试模式设置初始化顺序答题按钮状态
            if (settings.examMode === 'exam') {
                // 考试模式下禁用顺序答题按钮
                document.getElementById('navNormal').style.pointerEvents = 'none';
                document.getElementById('navNormal').style.opacity = '0.5';
            } else {
                // 正常模式下恢复顺序答题按钮
                document.getElementById('navNormal').style.pointerEvents = 'auto';
                document.getElementById('navNormal').style.opacity = '1';
            }
            
            // 根据设置决定启动模式
            if (settings.examMode === 'exam') {
                // 考试模式
                switchMode('exam');
            } else {
                // 正常模式，默认启动顺序答题
                switchMode('normal');
            }
        }
        
        // 保存错题到localStorage
        function saveWrongQuestions() {
            localStorage.setItem('wrongQuestions', JSON.stringify(wrongQuestions));
        }
        
        // 保存用户统计数据到localStorage
        function saveUserStats() {
            localStorage.setItem('userStats', JSON.stringify(userStats));
        }
        
        // 模式切换函数
        function switchMode(mode) {
            // 停止当前计时器
            stopTimer();
            
            // 移除所有导航项的active类
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 隐藏所有界面
            document.getElementById('modeSelection').style.display = 'none';
            document.getElementById('quizContainer').style.display = 'none';
            document.getElementById('resultScreen').style.display = 'none';
            document.getElementById('controls').style.display = 'none';
            document.getElementById('settingsScreen').style.display = 'none';
            
            // 根据模式显示对应界面
            switch(mode) {
                case 'normal':
                    currentMode = 'normal';
                    document.getElementById('navNormal').classList.add('active');
                    // 应用刷题数量设置
                    let normalQuestions = [...originalQuestions];
                    if (settings.questionCount && settings.questionCount < normalQuestions.length) {
                        normalQuestions = normalQuestions.slice(0, settings.questionCount);
                    }
                    questions = normalQuestions;
                    resetQuiz();
                    document.getElementById('quizContainer').style.display = 'block';
                    document.getElementById('controls').style.display = 'flex';
                    displayQuestion();
                    document.querySelector('.app-title').textContent = '顺序答题';
                    
                    // 启动计时器（如果启用）
                    if (settings.timerEnabled) {
                        startTimer();
                    }
                    
                    // 显示交卷按钮
                    document.getElementById('finishBtn').style.display = 'block';
                    break;
                case 'random':
                    currentMode = 'random';
                    document.getElementById('navRandom').classList.add('active');
                    // 应用刷题数量设置
                    let randomQuestions = [...originalQuestions];
                    // 随机打乱题目顺序
                    for (let i = randomQuestions.length - 1; i > 0; i--) {
                        const j = Math.floor(Math.random() * (i + 1));
                        [randomQuestions[i], randomQuestions[j]] = [randomQuestions[j], randomQuestions[i]];
                    }
                    if (settings.questionCount && settings.questionCount < randomQuestions.length) {
                        randomQuestions = randomQuestions.slice(0, settings.questionCount);
                    }
                    questions = randomQuestions;
                    resetQuiz();
                    document.getElementById('quizContainer').style.display = 'block';
                    document.getElementById('controls').style.display = 'flex';
                    displayQuestion();
                    document.querySelector('.app-title').textContent = '随机答题';
                    
                    // 启动计时器（如果启用）
                    if (settings.timerEnabled) {
                        startTimer();
                    }
                    
                    // 显示交卷按钮
                    document.getElementById('finishBtn').style.display = 'block';
                    break;
                case 'wrong':
                    currentMode = 'wrong';
                    document.getElementById('navWrong').classList.add('active');
                    if (wrongQuestions.length === 0) {
                        alert('暂无错题记录');
                        // 切换回顺序答题模式
                        switchMode('normal');
                        return;
                    }
                    questions = [...wrongQuestions];
                    resetQuiz();
                    document.getElementById('quizContainer').style.display = 'block';
                    document.getElementById('controls').style.display = 'flex';
                    displayQuestion();
                    document.querySelector('.app-title').textContent = '错题练习';
                    
                    // 启动计时器（如果启用）
                    if (settings.timerEnabled) {
                        startTimer();
                    }
                    
                    // 显示交卷按钮
                    document.getElementById('finishBtn').style.display = 'block';
                    break;
                case 'settings':
                    currentMode = 'settings';
                    document.getElementById('navSettings').classList.add('active');
                    document.getElementById('settingsScreen').style.display = 'flex';
                    document.querySelector('.app-title').textContent = '设置';
                    updateSettingsInfo();
                    
                    // 隐藏交卷按钮
                    document.getElementById('finishBtn').style.display = 'none';
                    break;
                case 'exam':
                    currentMode = 'exam';
                    document.getElementById('navNormal').classList.add('active'); // 使用顺序答题的导航状态
                    // 考试模式：固定40个单选、20个判断、20个多选
                    questions = getExamModeQuestions();
                    resetQuiz();
                    document.getElementById('quizContainer').style.display = 'block';
                    document.getElementById('controls').style.display = 'flex';
                    displayQuestion();
                    document.querySelector('.app-title').textContent = '考试模式';
                    
                    // 考试模式强制启动计时器
                    startTimer();
                    
                    // 显示交卷按钮
                    document.getElementById('finishBtn').style.display = 'block';
                    break;
            }
        }
        
        // 启动顺序答题模式（保留原有函数以兼容）
        function startNormalMode() {
            switchMode('normal');
        }
        
        // 启动随机答题模式（保留原有函数以兼容）
        function startRandomMode() {
            switchMode('random');
        }
        
        // 启动错题本模式（保留原有函数以兼容）
        function startWrongMode() {
            switchMode('wrong');
        }
        
        // 更新设置界面信息
        function updateSettingsInfo() {
            document.getElementById('totalQuestions').textContent = originalQuestions.length;
            document.getElementById('wrongCount').textContent = wrongQuestions.length;
            document.getElementById('completedCount').textContent = userStats.completedQuestionsList.length;
            
            // 更新设置选项的显示值
            document.getElementById('questionCount').value = settings.questionCount;
            document.getElementById('examMode').checked = settings.examMode === 'exam';
            document.getElementById('timerEnabled').checked = settings.timerEnabled;
        }
        
        // 保存刷题数量设置
        function saveQuestionCount() {
            settings.questionCount = parseInt(document.getElementById('questionCount').value);
            localStorage.setItem('settings', JSON.stringify(settings));
            console.log('保存刷题数量设置:', settings.questionCount);
        }
        
        // 保存答题模式设置
        function saveExamMode() {
            const examModeCheckbox = document.getElementById('examMode');
            settings.examMode = examModeCheckbox.checked ? 'exam' : 'normal';
            
            // 如果开启考试模式，自动将刷题数量改为80并禁用顺序答题按钮
            if (settings.examMode === 'exam') {
                settings.questionCount = 80;
                document.getElementById('questionCount').value = 80;
                // 禁用顺序答题按钮
                document.getElementById('navNormal').style.pointerEvents = 'none';
                document.getElementById('navNormal').style.opacity = '0.5';
            } else {
                // 恢复顺序答题按钮的可用状态
                document.getElementById('navNormal').style.pointerEvents = 'auto';
                document.getElementById('navNormal').style.opacity = '1';
                
                // 恢复刷题数量为默认值20题
                settings.questionCount = 20;
                document.getElementById('questionCount').value = 20;
            }
            
            localStorage.setItem('settings', JSON.stringify(settings));
            console.log('保存答题模式设置:', settings.examMode);
        }
        
        // 保存计时器设置
        function saveTimerSetting() {
            settings.timerEnabled = document.getElementById('timerEnabled').checked;
            localStorage.setItem('settings', JSON.stringify(settings));
            console.log('保存计时器设置:', settings.timerEnabled);
            
            // 如果当前在答题界面，立即应用计时器设置
            if (currentMode === 'normal' || currentMode === 'random' || currentMode === 'wrong') {
                if (settings.timerEnabled) {
                    startTimer();
                } else {
                    stopTimer();
                }
            }
        }
        
        // 启动计时器
        function startTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
            }
            
            timerSeconds = 0;
            timerInterval = setInterval(() => {
                timerSeconds++;
                updateTimerDisplay();
            }, 1000);
            
            console.log('计时器已启动');
        }
        
        // 停止计时器
        function stopTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
                timerInterval = null;
                console.log('计时器已停止');
            }
        }
        
        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(timerSeconds / 60);
            const seconds = timerSeconds % 60;
            const timeText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            // 在题目编号右侧显示计时器
            const timerDisplay = document.getElementById('timerDisplay');
            if (timerDisplay) {
                timerDisplay.textContent = timeText;
            }
        }
        
        // 获取考试模式的题目
        function getExamModeQuestions() {
            // 从原始题库中筛选不同类型的题目
            const singleChoiceQuestions = originalQuestions.filter(q => q.type === 'single_choice' || !q.type || (q.answer && !q.answer.includes(',')));
            const multipleChoiceQuestions = originalQuestions.filter(q => q.type === 'multiple_choice' || (q.answer && q.answer.includes(',')));
            const judgmentQuestions = originalQuestions.filter(q => q.type === 'true_false');
            
            console.log(`题库统计：单选${singleChoiceQuestions.length}题，多选${multipleChoiceQuestions.length}题，判断${judgmentQuestions.length}题`);
            
            // 计算需要的题目数量
            const totalNeeded = 80;
            const singleNeeded = Math.min(40, singleChoiceQuestions.length);
            const multipleNeeded = Math.min(20, multipleChoiceQuestions.length);
            const judgmentNeeded = Math.min(20, judgmentQuestions.length);
            
            // 计算已选题目数量
            let selectedCount = singleNeeded + multipleNeeded + judgmentNeeded;
            let remainingNeeded = totalNeeded - selectedCount;
            
            // 随机选择题目
            const selectedSingle = getRandomItems(singleChoiceQuestions, singleNeeded);
            const selectedMultiple = getRandomItems(multipleChoiceQuestions, multipleNeeded);
            const selectedJudgment = getRandomItems(judgmentQuestions, judgmentNeeded);
            
            // 如果题目不足，从所有题目中随机选择补充
            let supplementQuestions = [];
            if (remainingNeeded > 0) {
                const allSelected = [...selectedSingle, ...selectedMultiple, ...selectedJudgment];
                const availableQuestions = originalQuestions.filter(q => !allSelected.includes(q));
                supplementQuestions = getRandomItems(availableQuestions, remainingNeeded);
                selectedCount += supplementQuestions.length;
            }
            
            // 合并并打乱顺序
            let examQuestions = [...selectedSingle, ...selectedMultiple, ...selectedJudgment, ...supplementQuestions];
            examQuestions = shuffleArray(examQuestions);
            
            console.log(`考试模式题目：单选${selectedSingle.length}题，多选${selectedMultiple.length}题，判断${selectedJudgment.length}题，补充${supplementQuestions.length}题，总计${examQuestions.length}题`);
            return examQuestions;
        }
        
        // 从数组中随机选择指定数量的元素
        function getRandomItems(array, count) {
            const shuffled = [...array];
            for (let i = shuffled.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
            }
            return shuffled.slice(0, Math.min(count, shuffled.length));
        }
        
        // 打乱数组顺序
        function shuffleArray(array) {
            const shuffled = [...array];
            for (let i = shuffled.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
            }
            return shuffled;
        }
        
        // 清除错题记录
        function clearWrongQuestions() {
            console.log('开始清除错题记录，当前错题数量:', wrongQuestions.length);
            if (confirm('确定要清除所有错题记录吗？')) {
                wrongQuestions = [];
                console.log('错题数组已清空，开始保存到localStorage');
                try {
                    saveWrongQuestions();
                    console.log('错题已保存到localStorage，开始更新界面信息');
                    updateSettingsInfo();
                    console.log('界面信息已更新，显示提示信息');
                    alert('错题记录已清除');
                    console.log('清除错题记录完成');
                } catch (error) {
                    console.error('清除错题记录时发生错误:', error);
                    alert('清除错题记录失败，请重试');
                }
            }
        }

        // 重置答题状态
        function resetQuiz() {
            currentQuestion = 0;
            userAnswers = {};
            score = 0;
            answerSubmitted = {};
            document.getElementById('submitBtn').style.display = 'none';
            document.getElementById('answerHint').style.display = 'none';
            
            // 重置计时器显示
            const timerDisplay = document.getElementById('timerDisplay');
            if (timerDisplay) {
                timerDisplay.textContent = '';
            }
        }

        function initApp() {
            loadQuestions().catch(error => {
                console.error('初始化失败:', error);
                document.getElementById('loadingText').textContent = '加载失败，请检查网络连接';
            });
        }

        function displayQuestion() {
            const question = questions[currentQuestion];
            
            // 显示题号和题型
            let questionTypeText = '';
            if (question.type === 'single_choice') {
                questionTypeText = '（单选题）';
            } else if (question.type === 'multiple_choice') {
                questionTypeText = '（多选题）';
            } else if (question.type === 'true_false') {
                questionTypeText = '（判断题）';
            } else {
                questionTypeText = '（单选题）'; // 默认为单选题
            }
            document.getElementById('questionNumber').innerHTML = `第${currentQuestion + 1}题${questionTypeText}<span id="timerDisplay" style="margin-left: auto; color: #667eea;"></span>`;
            
            // 更新计时器显示
            updateTimerDisplay();
            
            document.getElementById('questionText').textContent = question.question;
            document.getElementById('progress').textContent = `${currentQuestion + 1}/${questions.length}`;
            
            const optionsContainer = document.getElementById('optionsContainer');
            optionsContainer.innerHTML = '';
            
            question.options.forEach((option, index) => {
                const optionDiv = document.createElement('div');
                optionDiv.className = 'option-btn';
                // 新格式：option是对象，包含label和text
                const optionText = typeof option === 'object' ? `${option.label}. ${option.text}` : option;
                optionDiv.textContent = optionText;
                optionDiv.onclick = () => selectAnswer(index);
                
                // 恢复之前的选择状态和提交状态
                if (question.type === 'multiple_choice') {
                    // 多选题：检查是否在已选答案中
                    if (userAnswers[currentQuestion] && userAnswers[currentQuestion].includes(index)) {
                        if (answerSubmitted[currentQuestion]) {
                            // 如果已提交，显示正确/错误状态
                            const correctAnswers = getCorrectAnswers(question);
                            if (correctAnswers.includes(index)) {
                                optionDiv.classList.add('correct');
                            } else {
                                optionDiv.classList.add('incorrect');
                            }
                        } else {
                            // 如果未提交，显示选中状态
                            optionDiv.classList.add('selected');
                        }
                    }
                } else {
                    // 单选题：检查是否是唯一选择的答案
                    if (userAnswers[currentQuestion] === index) {
                        if (answerSubmitted[currentQuestion]) {
                            // 如果已提交，显示正确/错误状态
                            let correctIndex = -1;
                            if (typeof question.options[0] === 'object') {
                                correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                            } else {
                                correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                            }
                            
                            if (index === correctIndex) {
                                optionDiv.classList.add('correct');
                            } else if (index === userAnswers[currentQuestion] && index !== correctIndex) {
                                optionDiv.classList.add('incorrect');
                            }
                        } else {
                            // 如果未提交，显示选中状态
                            optionDiv.classList.add('selected');
                        }
                    }
                }
                
                optionsContainer.appendChild(optionDiv);
            });
            
            // 更新按钮状态
            document.getElementById('prevBtn').disabled = currentQuestion === 0;
            document.getElementById('nextBtn').textContent = 
                currentQuestion === questions.length - 1 ? '完成' : '下一题';
            
            // 更新确定按钮和答案提示显示状态
            if (answerSubmitted[currentQuestion]) {
                // 已提交答案，显示答案提示，隐藏确定按钮
                document.getElementById('submitBtn').style.display = 'none';
                
                // 重新显示答案提示
                const answerHint = document.getElementById('answerHint');
                
                if (question.type === 'multiple_choice') {
                    // 多选题答案验证
                    const userAnswerIndexes = userAnswers[currentQuestion] || [];
                    const correctAnswerIndexes = getCorrectAnswers(question);
                    
                    // 检查答案是否完全正确
                    const isCorrect = userAnswerIndexes.length === correctAnswerIndexes.length &&
                                    userAnswerIndexes.every(index => correctAnswerIndexes.includes(index));
                    
                    // 构建正确答案文本
                    const correctAnswerText = correctAnswerIndexes.map(index => {
                        return typeof question.options[index] === 'object' 
                            ? question.options[index].label 
                            : question.options[index].charAt(0);
                    }).join('');
                    
                    if (isCorrect) {
                        answerHint.textContent = `正确答案：${correctAnswerText}`;
                        answerHint.style.background = 'rgba(40, 167, 69, 0.3)';
                    } else {
                        answerHint.textContent = `正确答案：${correctAnswerText}`;
                        answerHint.style.background = 'rgba(220, 53, 69, 0.3)';
                    }
                } else {
                    // 单选题答案验证
                    const userAnswerIndex = userAnswers[currentQuestion];
                    let correctIndex = -1;
                    if (typeof question.options[0] === 'object') {
                        correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                    } else {
                        correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                    }
                    
                    if (userAnswerIndex === correctIndex) {
                        answerHint.textContent = `正确答案：${question.answer}`;
                        answerHint.style.background = 'rgba(40, 167, 69, 0.3)';
                    } else {
                        answerHint.textContent = `正确答案：${question.answer}`;
                        answerHint.style.background = 'rgba(220, 53, 69, 0.3)';
                    }
                }
                answerHint.style.display = 'block';
            } else {
                // 未提交答案，根据是否选择了答案来显示确定按钮
                const question = questions[currentQuestion];
                if (userAnswers[currentQuestion] !== undefined && 
                    (question.type !== 'multiple_choice' || userAnswers[currentQuestion].length > 0)) {
                    document.getElementById('submitBtn').style.display = 'block';
                } else {
                    document.getElementById('submitBtn').style.display = 'none';
                }
                document.getElementById('answerHint').style.display = 'none';
            }
        }
        
        function selectAnswer(index) {
            const question = questions[currentQuestion];
            
            // 初始化当前题目的答案数组（如果是多选题）
            if (userAnswers[currentQuestion] === undefined) {
                userAnswers[currentQuestion] = [];
            }
            
            // 根据题型处理选择逻辑
            if (question.type === 'multiple_choice') {
                // 多选题：可以多选
                const currentAnswers = userAnswers[currentQuestion];
                const answerIndex = currentAnswers.indexOf(index);
                
                if (answerIndex > -1) {
                    // 如果已选择，则取消选择
                    currentAnswers.splice(answerIndex, 1);
                } else {
                    // 如果未选择，则添加选择
                    currentAnswers.push(index);
                }
                
                // 如果没有选择任何选项，则设置为undefined
                if (currentAnswers.length === 0) {
                    userAnswers[currentQuestion] = undefined;
                }
            } else {
                // 单选题：只能选择一个
                userAnswers[currentQuestion] = index;
            }
            
            // 更新选项样式
            const options = document.querySelectorAll('.option-btn');
            options.forEach((option, i) => {
                option.classList.remove('selected', 'correct', 'incorrect');
                
                if (question.type === 'multiple_choice') {
                    // 多选题：检查是否在已选答案中
                    if (userAnswers[currentQuestion] && userAnswers[currentQuestion].includes(i)) {
                        option.classList.add('selected');
                    }
                } else {
                    // 单选题：检查是否是唯一选择的答案
                    if (userAnswers[currentQuestion] === i) {
                        option.classList.add('selected');
                    }
                }
            });
            
            // 显示确定按钮（只要有选择就显示）
            if (userAnswers[currentQuestion] !== undefined && 
                (question.type !== 'multiple_choice' || userAnswers[currentQuestion].length > 0)) {
                document.getElementById('submitBtn').style.display = 'block';
            } else {
                document.getElementById('submitBtn').style.display = 'none';
            }
            
            // 隐藏答案提示
            document.getElementById('answerHint').style.display = 'none';
        }
        
        // 获取多选题的正确答案索引数组
        function getCorrectAnswers(question) {
            if (question.type === 'multiple_choice') {
                // 多选题：answer可能是逗号分隔的字符串，如"A,B,C"，或者是数组
                let correctLabels;
                if (typeof question.answer === 'string') {
                    correctLabels = question.answer.split(',').map(label => label.trim());
                } else if (Array.isArray(question.answer)) {
                    correctLabels = question.answer;
                } else {
                    // 如果answer不是字符串也不是数组，尝试转换为字符串
                    correctLabels = String(question.answer || '').split(',').map(label => label.trim());
                }
                
                return correctLabels.map(label => {
                    return question.options.findIndex(opt => {
                        if (typeof opt === 'object') {
                            return opt.label === label;
                        } else {
                            return opt.startsWith(label);
                        }
                    });
                }).filter(index => index !== -1); // 过滤掉无效的索引
            } else {
                // 单选题：返回单个索引的数组
                let correctIndex = -1;
                if (typeof question.options[0] === 'object') {
                    correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                } else {
                    correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                }
                return correctIndex !== -1 ? [correctIndex] : [];
            }
        }
        
        function submitAnswer() {
            const question = questions[currentQuestion];
            
            if (userAnswers[currentQuestion] === undefined) {
                alert('请先选择答案');
                return;
            }
            
            // 标记答案已提交
            answerSubmitted[currentQuestion] = true;
            
            // 获取正确答案
            const correctAnswerIndexes = getCorrectAnswers(question);
            
            // 验证答案是否正确
            let isCorrect = false;
            if (question.type === 'multiple_choice') {
                const userAnswerIndexes = userAnswers[currentQuestion] || [];
                isCorrect = userAnswerIndexes.length === correctAnswerIndexes.length &&
                           userAnswerIndexes.every(index => correctAnswerIndexes.includes(index));
            } else {
                const userAnswerIndex = userAnswers[currentQuestion];
                isCorrect = userAnswerIndex === correctAnswerIndexes[0];
            }
            
            // 更新选项样式显示结果（参照电脑端样式）
            const options = document.querySelectorAll('.option-btn');
            options.forEach((option, i) => {
                option.classList.remove('selected', 'correct-selected', 'correct-not-selected', 'incorrect');
                
                if (correctAnswerIndexes.includes(i)) {
                    // 正确答案
                    if (question.type === 'multiple_choice') {
                        if (userAnswers[currentQuestion] && userAnswers[currentQuestion].includes(i)) {
                            // 选中的正确答案
                            option.classList.add('correct-selected');
                        } else {
                            // 未选中的正确答案
                            option.classList.add('correct-not-selected');
                        }
                    } else {
                        // 单选题
                        if (userAnswers[currentQuestion] === i) {
                            // 选中的正确答案
                            option.classList.add('correct-selected');
                        } else {
                            // 未选中的正确答案
                            option.classList.add('correct-not-selected');
                        }
                    }
                } else if (question.type === 'multiple_choice') {
                    // 多选题：检查用户是否选择了错误的选项
                    if (userAnswers[currentQuestion] && userAnswers[currentQuestion].includes(i)) {
                        option.classList.add('incorrect');
                    }
                } else {
                    // 单选题：检查用户是否选择了错误的选项
                    if (userAnswers[currentQuestion] === i) {
                        option.classList.add('incorrect');
                    }
                }
            });
            
            // 在标题处显示答案提示
            const answerHint = document.getElementById('answerHint');
            
            if (question.type === 'multiple_choice') {
                // 多选题答案验证
                const correctAnswerText = correctAnswerIndexes.map(index => {
                    return typeof question.options[index] === 'object' 
                        ? question.options[index].label 
                        : question.options[index].charAt(0);
                }).join('');
                
                answerHint.textContent = `正确答案：${correctAnswerText}`;
                answerHint.style.background = isCorrect ? 'rgba(40, 167, 69, 0.3)' : 'rgba(220, 53, 69, 0.3)';
            } else {
                // 单选题答案验证
                answerHint.textContent = `正确答案：${question.answer}`;
                answerHint.style.background = isCorrect ? 'rgba(40, 167, 69, 0.3)' : 'rgba(220, 53, 69, 0.3)';
            }
            answerHint.style.display = 'block';
            
            // 更新用户统计数据（参照电脑端实现）
            if (!settings.examMode) {
                // 非考试模式下，每道题确认时计数
                if (!userStats.completedQuestionsList) userStats.completedQuestionsList = [];
                if (!userStats.completedQuestionsList.includes(question.id)) {
                    userStats.completedQuestionsList.push(question.id);
                    userStats.completedQuestions = Math.min(userStats.completedQuestionsList.length, originalQuestions.length);
                    
                    // 更新正确答题数
                    if (isCorrect) {
                        userStats.correctAnswers = Math.min(userStats.correctAnswers + 1, userStats.completedQuestions);
                    }
                    
                    saveUserStats();
                    if (currentMode === 'settings') {
                        updateSettingsInfo();
                    }
                    console.log('已完成题目更新：', userStats.completedQuestions);
                }
            }
            
            // 更新错题本（参照电脑端实现）
            if (isCorrect) {
                // 答对了，从错题本移除
                const wrongIndex = wrongQuestions.findIndex(wq => wq.id === question.id);
                if (wrongIndex > -1) {
                    wrongQuestions.splice(wrongIndex, 1);
                    saveWrongQuestions();
                    console.log('从错题本中移除已答对的题目');
                    if (currentMode === 'settings') {
                        updateSettingsInfo();
                    }
                }
            } else {
                // 答错了，添加到错题本
                const isAlreadyWrong = wrongQuestions.some(wq => wq.id === question.id);
                if (!isAlreadyWrong) {
                    wrongQuestions.push(question);
                    saveWrongQuestions();
                    console.log('添加错题到错题本');
                    if (currentMode === 'settings') {
                        updateSettingsInfo();
                    }
                }
            }
            
            // 隐藏确定按钮
            document.getElementById('submitBtn').style.display = 'none';
            
            // 参照电脑端：答对时自动跳转，答错时停留
            if (isCorrect) {
                setTimeout(() => {
                    if (currentQuestion < questions.length - 1) {
                        nextQuestion();
                    } else {
                        finishQuiz();
                    }
                }, 1000);
            }
            // 答错时不跳转，用户需要手动点击下一题按钮
        }

        function previousQuestion() {
            if (currentQuestion > 0) {
                currentQuestion--;
                displayQuestion();
            }
        }
        
        function nextQuestion() {
            if (currentQuestion < questions.length - 1) {
                currentQuestion++;
                displayQuestion();
            } else {
                finishQuiz();
            }
        }

        function finishQuiz() {
    score = 0;
    for (let i = 0; i < questions.length; i++) {
        if (userAnswers[i] !== undefined) {
            const question = questions[i];
            
            if (settings.examMode === 'exam') {
                // 考试模式评分规则
                if (question.type === 'multiple_choice') {
                    // 多选题：答对1项得0.5分，2项得1分，3项得1.5分，完全答对得2分，选了错误答案得0分
                    const userAnswerIndexes = userAnswers[i] || [];
                    const correctAnswerIndexes = getCorrectAnswers(question);
                    
                    // 检查是否选择了错误答案
                    const hasWrongAnswer = userAnswerIndexes.some(index => !correctAnswerIndexes.includes(index));
                    
                    if (hasWrongAnswer) {
                        // 选了错误答案，得0分
                        continue;
                    }
                    
                    // 计算答对的数量
                    const correctCount = userAnswerIndexes.filter(index => correctAnswerIndexes.includes(index)).length;
                    
                    // 根据答对数量计分
                    if (correctCount === 1) {
                        score += 0.5;
                    } else if (correctCount === 2) {
                        score += 1;
                    } else if (correctCount === 3) {
                        score += 1.5;
                    } else if (correctCount === correctAnswerIndexes.length && correctCount > 0) {
                        // 完全答对
                        score += 2;
                    }
                } else if (question.type === 'true_false') {
                    // 判断题：正确得1分
                    let correctIndex = -1;
                    if (typeof question.options[0] === 'object') {
                        correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                    } else {
                        correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                    }
                    
                    if (userAnswers[i] === correctIndex) {
                        score += 1;
                    }
                } else {
                    // 单选题：正确得1分
                    let correctIndex = -1;
                    if (typeof question.options[0] === 'object') {
                        correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                    } else {
                        correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                    }
                    
                    if (userAnswers[i] === correctIndex) {
                        score += 1;
                    }
                }
            } else {
                // 普通模式评分规则
                if (question.type === 'multiple_choice') {
                    // 多选题答案验证
                    const userAnswerIndexes = userAnswers[i] || [];
                    const correctAnswerIndexes = getCorrectAnswers(question);
                    
                    // 检查答案是否完全正确（所有正确答案都选中，且没有选错答案）
                    const isCorrect = userAnswerIndexes.length === correctAnswerIndexes.length &&
                                    userAnswerIndexes.every(index => correctAnswerIndexes.includes(index));
                    
                    if (isCorrect) {
                        score++;
                    }
                } else {
                    // 单选题答案验证
                    let correctIndex = -1;
                    
                    // 新格式：答案是标签，直接匹配
                    if (typeof question.options[0] === 'object') {
                        correctIndex = question.options.findIndex(opt => opt.label === question.answer);
                    } else {
                        // 兼容旧格式：检查选项是否以答案开头
                        correctIndex = question.options.findIndex(opt => opt.startsWith(question.answer));
                    }
                    
                    if (userAnswers[i] === correctIndex) {
                        score++;
                    }
                }
            }
        }
    }
    
    document.getElementById('quizContainer').style.display = 'none';
    document.getElementById('controls').style.display = 'none';
    document.getElementById('resultScreen').style.display = 'flex';
    
    // 根据模式计算总分和百分比
    let totalScore;
    let percentage;
    
    if (settings.examMode === 'exam') {
        // 考试模式：总分100分
        totalScore = 100;
        percentage = Math.round(score);
    } else {
        // 普通模式：总分等于题目数量
        totalScore = questions.length;
        percentage = Math.round((score / questions.length) * 100);
    }
    
    document.getElementById('finalScore').textContent = `${percentage}分`;
    
    // 根据不同模式显示不同的结果文本
    let resultText = '恭喜您完成所有题目';
    if (currentMode === 'random') {
        resultText = '恭喜您完成随机答题';
    } else if (currentMode === 'wrong') {
        resultText = '恭喜您完成错题练习';
    }
    document.getElementById('resultText').textContent = resultText;
    
    // 更新已完成题目数量（参照电脑端实现）
    if (!userStats.completedQuestionsList) {
        userStats.completedQuestionsList = [];
    }
    
    // 计算本次完成的题目
    const answeredQuestions = questions.filter(q => userAnswers[questions.indexOf(q)] !== undefined);
    const newlyCompleted = answeredQuestions.filter(q => !userStats.completedQuestionsList.includes(q.id));
    
    newlyCompleted.forEach(q => {
        userStats.completedQuestionsList.push(q.id);
    });
    
    // 确保completedQuestions与completedQuestionsList长度一致
    userStats.completedQuestions = Math.min(userStats.completedQuestionsList.length, originalQuestions.length);
    
    // 更新正确答题数量
    const correctCount = answeredQuestions.filter(q => {
        const index = questions.indexOf(q);
        const correctAnswerIndexes = getCorrectAnswers(q);
        
        if (q.type === 'multiple_choice') {
            const userAnswerIndexes = userAnswers[index] || [];
            return userAnswerIndexes.length === correctAnswerIndexes.length &&
                   userAnswerIndexes.every(idx => correctAnswerIndexes.includes(idx));
        } else {
            return userAnswers[index] === correctAnswerIndexes[0];
        }
    }).length;
    
    userStats.correctAnswers = Math.min(userStats.correctAnswers + correctCount, userStats.completedQuestions);
    
    // 保存用户统计数据
    saveUserStats();
    
    // 如果当前在设置界面，更新显示
    if (currentMode === 'settings') {
        updateSettingsInfo();
    }
    
    // 确保当前模式的导航项保持激活状态
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
    });
    
    switch(currentMode) {
        case 'normal':
            document.getElementById('navNormal').classList.add('active');
            break;
        case 'random':
            document.getElementById('navRandom').classList.add('active');
            break;
        case 'wrong':
            document.getElementById('navWrong').classList.add('active');
            break;
        case 'settings':
            document.getElementById('navSettings').classList.add('active');
            break;
    }
}

        function restartQuiz() {
            // 根据当前模式重新开始
            switchMode(currentMode);
        }

        // 启动应用
        initApp();
    </script>
    <!-- 静态加载题库数据，确保直接双击运行时能够正常加载 -->
    <script src="./questions.js"></script>
</body>
</html>